﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;
using System.Web.UI.WebControls;

namespace ZWZ.Web.Codes
{
    public class UploadFileHelper
    {
        private static Regex Regex_ImageFile = new Regex("^.+\\.((jpg)|(png)|(jpeg)|(gif)|(bmp))$");
        private static Regex Regex_DocFile = new Regex("^.+\\.((doc)|(docx)|(wps)|(txt)|(xls)|(xlsx)|(pdf))$");
        private static Regex Regex_VideoFile = new Regex("^.+\\.((rm)|(rmvb)|(wmv)|(flv)|(swf))$");
        private static Regex Regex_AudioFile = new Regex("^.+\\.((mp3)|(wma))$");
        private static Regex Regex_FibbitFile = new Regex("^.+\\.((exe)|(com)|(bat)|(js)|(vbs)|(reg))$");
        private const string FILESAVEPATH = "/Files/";
        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath)
        {
            if (strPath.ToLower().StartsWith("http://"))
            {
                return strPath;
            }
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                strPath = strPath.Replace("/", "\\");
                if (strPath.StartsWith("\\"))
                {
                    strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
                }
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }
        /// <summary>
        /// 根据类型取得扩展名
        /// </summary>
        /// <param name="filetype"></param>
        /// <returns></returns>
        private static Regex GetFileRegex(UpLoadFileType filetype)
        {
            switch (filetype)
            {
                case UpLoadFileType.Image:
                    return Regex_ImageFile;
                case UpLoadFileType.Audio:
                    return Regex_AudioFile;
                case UpLoadFileType.Document:
                    return Regex_DocFile;
                case UpLoadFileType.Video:
                    return Regex_VideoFile;
                case UpLoadFileType.Default:
                    return Regex_FibbitFile;
                default:
                    return null;
            }
        }
        /// <summary>
        /// 检查文件扩展名
        /// </summary>
        /// <param name="filetype"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static bool CheckFile(UpLoadFileType filetype, string filename)
        {
            if (filetype == UpLoadFileType.Default) { return !GetFileRegex(filetype).IsMatch(filename); }
            return GetFileRegex(filetype).IsMatch(filename);
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileSource">源上传控件</param>
        /// <param name="SavePath">存储目录</param>
        /// <param name="NewName">新文件名</param>
        /// <returns>新文件路径</returns>
        public static string UpLoadFile(string DirID, string ContentID, HttpPostedFile fileSource, UpLoadFileType filetype)
        {
            string fileName = Path.GetFileName(fileSource.FileName);
            string Ext = Path.GetExtension(fileName);
            if (!CheckFile(filetype, fileName)) { throw new Exception("文件格式错误!"); }
            string SavePath = FILESAVEPATH + filetype.ToString() + "/" + Guid.NewGuid().ToString() + Ext;
            string PhySavePath = GetMapPath(SavePath);
            fileSource.SaveAs(PhySavePath);
            var fileinfo = new ModelBase.File_Info()
            {
                ContentID = ContentID,
                CreateTime = DateTime.Now,
                CUserID = LoginHelper.CurrentUser.ID,
                CUserName = LoginHelper.CurrentUser.NickName,
                DirID = DirID,
                Ext = Ext.Substring(1),
                Path = SavePath,
                Size = fileSource.ContentLength,
                Type = filetype.ToString(),
                Name = fileName,
                ID = Codes.IDHelper.CreateID_FileInfo()
            };
            DBProvider.DB.Ctx.File_Info.AddObject(fileinfo);
            DBProvider.DB.Ctx.SaveChanges();
            return SavePath;
        }
    }

    public enum UpLoadFileType
    {
        Image,
        Document,
        Video,
        Audio,
        Default
    }
}